<template>
  <div class="drawer-slot" v-loading="loading">
    <el-form ref="refNewsForm" :rules="rules" :model="newsForm" label-width="90px">
      <el-form-item label="文章标题:" prop="title">
        <el-input v-model.trim="newsForm.title" />
      </el-form-item>
      <el-form-item label="文章封面:" prop="cover">
        <el-upload
          class="cover-uploader"
          :show-file-list="false"
          :http-request="addCover"
          :before-upload="beforeUpload"
          action="action"
        >
          <img v-if="newsForm.cover" :src="newsForm.cover" class="cover" />
          <el-button type="primary" v-else>上传封面</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容:" prop="content">
        <div style="border: 1px solid #ccc; margin-top: 10px">
          <!-- 工具栏 -->
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <!-- 编辑器 -->
          <Editor
            v-model="newsForm.content"
            style="height: 400px; overflow-y: hidden"
            :defaultConfig="editorConfig"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(refNewsForm)">提交</el-button>
        <el-button @click="onCancel">关闭</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, shallowRef, onBeforeUnmount, onMounted, watchEffect } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import useUserStore from '@/stores/modules/user'
import { addNews, uploadCover, getOneNews, updateOneNews } from '@/api/news'
const emit = defineEmits(['updateNewsData', 'closeDrawer'])
const loading = ref(false)
import { ElMessage } from 'element-plus'
defineOptions({ name: 'newsDrawerSlot' })

const userStore = useUserStore()
const refNewsForm = ref(null)
const props = defineProps({
  drawerStatus: {
    type: String,
    default: ''
  },
  editId: {
    type: String,
    default: ''
  }
})
const newsForm = ref({
  title: '',
  cover: '',
  content: ''
})
const formData = ref(null)
const onSubmit = function (formEl) {
  formEl.validate(async (valid) => {
    console.log('valid: ', valid)
    if (valid) {
      try {
        const response =
          props.drawerStatus === 'update'
            ? await updateOneNews(props.editId, newsForm.value)
            : await addNews(newsForm.value)
        console.log('response: ', response)
        loading.value = false
        ElMessage({
          type: 'success',
          message: props.drawerStatus === 'update' ? '新闻修改成功' : '新闻添加成功'
        })
        emit('updateNewsData')
      } catch (error) {
        console.log('error: ', error)
        loading.value = false
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
const resetForm = function () {
  newsForm.value = {
    title: '',
    cover: '',
    content: ''
  }
}
const onCancel = function () {
  emit('closeDrawer')
}
const beforeUpload = (file) => {
  const type = file.name.substring(file.name.lastIndexOf('.') + 1)
  const typeInfo = ['jpg', 'png', 'jpeg']
  if (!typeInfo.includes(type)) {
    ElMessage({
      type: 'error',
      message: '只支持jpg,png,jpeg文件格式！'
    })
    return false
  }
  if (file.size / 1024 > 500) {
    ElMessage({ type: 'error', message: '图片不能大于500kb！' })
    return false
  }
  const createFormData = new FormData()
  createFormData.append('files', file)
  formData.value = createFormData
}
// 上传封面
const addCover = async () => {
  const postFormData = formData.value
  try {
    var result = await uploadCover(postFormData)
    newsForm.value.cover = result.data.imgUrl
    ElMessage({
      type: 'success',
      message: '封面添加成功'
    })
  } catch (error) {
    console.log('error: ', error)
  }
}

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  cover: [{ required: true, message: '请选择封面', trigger: 'blur' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
}
const editorRef = shallowRef()

const toolbarConfig = ref({ placeholder: '请输入内容...' })
const mode = ref('default')
const editorConfig = ref({
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      // 后端上传地址，必填
      server: 'http://127.0.0.1:3005/upload/news',
      customInsert(res, insertFn) {
        //  {"code":20000,"data":{"message":"添加新闻图片成功","imgUrl":"http://127.0.0.1:3005/news/avatar_1678197437113.png"}}
        // 从 res 中找到 url alt href ，然后插入图片
        const url = res.data.imgUrl
        insertFn(url)
      },
      fieldName: 'files',
      // 1M，单个文件的最大体积限制，默认为 2M
      maxFileSize: 1 * 1024 * 1024,
      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 1,
      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ['image/*'],
      // 15 秒，超时时间，默认为 10 秒
      timeout: 15 * 1000,
      headers: {
        Accept: 'text/x-json',
        Authorization: `Bearer ${userStore.token}`
      }
    }
  }
})
const handleCreated = (editor) => {
  editorRef.value = editor
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 拉编辑数据
const getEditInfo = async function (id) {
  try {
    var {
      data: { title, cover, content }
    } = await getOneNews(id)
    newsForm.value = { title, cover, content }
  } catch (error) {
    console.log('error: ', error)
  }
}

watchEffect(() => {
  console.log('props.drawerStatus: ', props.drawerStatus)
  if (props.drawerStatus === 'update') {
    getEditInfo(props.editId)
  }
})
onMounted(() => {
  console.log('props.editId: ', props.editId)
  if (props.editId) {
    getEditInfo(props.editId)
  }
})
defineExpose({
  resetForm
})
</script>

<style lang="scss" scoped></style>
